// 管理员仪表盘JavaScript

// API基础URL
const API_BASE_URL = '/api/v1/admin';

// DOM元素引用
const dashboardLink = document.getElementById('dashboardLink');
const usersLink = document.getElementById('usersLink');
const deliveryPersonsLink = document.getElementById('deliveryPersonsLink');
const ordersLink = document.getElementById('ordersLink');
const statisticsLink = document.getElementById('statisticsLink');
const logoutBtn = document.getElementById('logoutBtn');

const dashboardView = document.getElementById('dashboardView');
const usersView = document.getElementById('usersView');
const deliveryPersonsView = document.getElementById('deliveryPersonsView');
const ordersView = document.getElementById('ordersView');
const statisticsView = document.getElementById('statisticsView');

const totalUsers = document.getElementById('totalUsers');
const totalDeliveryPersons = document.getElementById('totalDeliveryPersons');
const totalOrders = document.getElementById('totalOrders');
const completedOrders = document.getElementById('completedOrders');

const recentOrdersTable = document.getElementById('recentOrdersTable');
const deliveryPersonsTable = document.getElementById('deliveryPersonsTable');
const refreshDashboard = document.getElementById('refreshDashboard');

// DOM元素引用 - 添加新的引用
const refreshUsers = document.getElementById('refreshUsers');
const refreshDeliveryPersons = document.getElementById('refreshDeliveryPersons');
const refreshOrders = document.getElementById('refreshOrders');
const refreshStatistics = document.getElementById('refreshStatistics');

const usersTable = document.getElementById('usersTable');
const deliveryPersonsFullTable = document.getElementById('deliveryPersonsFullTable');
const ordersTable = document.getElementById('ordersTable');

// 页面加载完成后执行
// 加载所有模块
document.addEventListener('DOMContentLoaded', function() {
    // 初始化仪表盘
    initDashboard();
});

    // 添加导航事件监听器
    dashboardLink.addEventListener('click', showDashboardView);
    usersLink.addEventListener('click', showUsersView);
    deliveryPersonsLink.addEventListener('click', showDeliveryPersonsView);
    ordersLink.addEventListener('click', showOrdersView);
    statisticsLink.addEventListener('click', showStatisticsView);
    logoutBtn.addEventListener('click', logout);
    refreshDashboard.addEventListener('click', loadDashboardData);
    
    // 添加新的事件监听器
    if (refreshUsers) refreshUsers.addEventListener('click', loadUsersData);
    if (refreshDeliveryPersons) refreshDeliveryPersons.addEventListener('click', loadDeliveryPersonsData);
    if (refreshOrders) refreshOrders.addEventListener('click', loadOrdersData);
    if (refreshStatistics) refreshStatistics.addEventListener('click', loadStatisticsData);
;

// 初始化仪表盘
function initDashboard() {
    // 检查用户是否已登录并具有管理员权限
    checkAdminAuth();
    
    // 加载仪表盘数据
    loadDashboardData();
}

// 检查管理员权限
// 检查管理员权限
async function checkAdminAuth() {
    console.log('跳过管理员权限检查');
    return true; // 直接返回true，完全跳过权限检查
    
    /* 原代码注释掉
    try {
        console.log('正在检查管理员权限...');
        
        const response = await fetch(`${API_BASE_URL}/check-auth`, {
            method: 'GET',
            credentials: 'same-origin',
            headers: {
                'Cache-Control': 'no-cache',
                'Pragma': 'no-cache'
            }
        });
        
        console.log('权限检查响应状态:', response.status, response.statusText);
        
        if (!response.ok) {
            console.error('管理员权限检查失败:', response.status, response.statusText);
            // 如果未授权，重定向到登录页面
            window.location.href = '/admin-login.html?error=auth_failed&status=' + response.status;
            return false;
        }
        
        const data = await response.json();
        console.log('权限检查响应数据:', data);
        console.log('管理员权限检查成功');
        return true;
    } catch (error) {
        console.error('检查权限失败:', error);
        // 暂时注释掉重定向代码
        // window.location.href = '/admin-login.html';
        console.log('出现错误，但暂时忽略并返回成功');
        return true;
    }
    */
}

// 加载仪表盘数据
async function loadDashboardData() {
    try {
        // 获取统计数据
        const statsResponse = await fetch(`${API_BASE_URL}/statistics`, {
            method: 'GET',
            credentials: 'same-origin'
        });
        
        if (statsResponse.ok) {
            const stats = await statsResponse.json();
            updateDashboardStats(stats);
        }
        
        // 获取最近订单
        const ordersResponse = await fetch(`${API_BASE_URL}/orders/recent`, {
            method: 'GET',
            credentials: 'same-origin'
        });
        
        if (ordersResponse.ok) {
            const orders = await ordersResponse.json();
            displayRecentOrders(orders);
        }
        
        // 获取配送员状态
        const deliveryPersonsResponse = await fetch(`${API_BASE_URL}/delivery-persons/active`, {
            method: 'GET',
            credentials: 'same-origin'
        });
        
        if (deliveryPersonsResponse.ok) {
            const deliveryPersons = await deliveryPersonsResponse.json();
            displayDeliveryPersons(deliveryPersons);
        }
    } catch (error) {
        console.error('加载仪表盘数据失败:', error);
        showAlert('加载仪表盘数据失败，请刷新页面重试。', 'danger');
    }
}

// 更新仪表盘统计数据
function updateDashboardStats(stats) {
    totalUsers.textContent = stats.totalUsers || 0;
    totalDeliveryPersons.textContent = stats.totalDeliveryPersons || 0;
    totalOrders.textContent = stats.totalOrders || 0;
    completedOrders.textContent = stats.completedOrders || 0;
}

// 显示最近订单
function displayRecentOrders(orders) {
    if (!orders || orders.length === 0) {
        recentOrdersTable.innerHTML = '<tr><td colspan="4" class="text-center">暂无订单数据</td></tr>';
        return;
    }
    
    const ordersHtml = orders.map(order => `
        <tr>
            <td>${order.orderNumber}</td>
            <td><span class="badge ${getOrderStatusBadgeClass(order.status)}">${formatOrderStatus(order.status)}</span></td>
            <td>${formatDate(order.creationTime)}</td>
            <td>
                <button class="btn btn-sm btn-outline-primary" onclick="viewOrderDetail('${order.orderNumber}')">查看</button>
            </td>
        </tr>
    `).join('');
    
    recentOrdersTable.innerHTML = ordersHtml;
}

// 显示配送员状态
function displayDeliveryPersons(deliveryPersons) {
    if (!deliveryPersons || deliveryPersons.length === 0) {
        deliveryPersonsTable.innerHTML = '<tr><td colspan="4" class="text-center">暂无配送员数据</td></tr>';
        return;
    }
    
    const deliveryPersonsHtml = deliveryPersons.map(person => `
        <tr>
            <td>${person.name}</td>
            <td>${person.phone}</td>
            <td><span class="badge ${getDeliveryPersonStatusBadgeClass(person.status)}">${formatDeliveryPersonStatus(person.status)}</span></td>
            <td>
                <button class="btn btn-sm btn-outline-primary" onclick="viewDeliveryPersonDetail('${person.id}')">查看</button>
            </td>
        </tr>
    `).join('');
    
    deliveryPersonsTable.innerHTML = deliveryPersonsHtml;
}

// 获取订单状态对应的徽章类
function getOrderStatusBadgeClass(status) {
    switch (status) {
        case 'PENDING':
            return 'bg-secondary';
        case 'PENDING_COLLECTION':
            return 'bg-info';
        case 'COLLECTED':
            return 'bg-primary';
        case 'IN_TRANSIT':
            return 'bg-primary';
        case 'OUT_FOR_DELIVERY':
            return 'bg-warning';
        case 'DELIVERED':
            return 'bg-success';
        case 'SIGNED':
            return 'bg-success';
        case 'CANCELLED':
            return 'bg-danger';
        default:
            return 'bg-secondary';
    }
}

// 格式化订单状态
function formatDeliveryPersonStatus(status) {
    const descriptions = {
        'IDLE': '空闲',
        'BUSY': '忙碌',
        'OFFLINE': '离线',
        'DELIVERING': '配送中'
    };
    
    return descriptions[status] || status;
}

// 格式化订单状态
function formatOrderStatus(status) {
    // 使用 getStatusDescription 函数来获取状态描述
    return getStatusDescription(status);
}

// 获取配送员状态对应的徽章类
function getDeliveryPersonStatusBadgeClass(status) {
    switch (status) {
        case 'IDLE':
            return 'bg-success';
        case 'BUSY':
            return 'bg-warning';
        case 'OFFLINE':
            return 'bg-secondary';
        default:
            return 'bg-secondary';
    }
}

// 格式化配送员状态
function formatDeliveryPersonStatus(status) {
    // 添加调试信息
    console.log('配送员状态值:', status, typeof status);
    
    // 如果状态是null或undefined，返回未知状态
    if (status === null || status === undefined) {
        return '未知状态';
    }
    
    // 处理可能的对象情况（如果后端返回的是完整的枚举对象）
    if (typeof status === 'object' && status !== null) {
        // 尝试获取可能的属性
        if (status.name) return formatDeliveryPersonStatus(status.name);
        if (status.value) return formatDeliveryPersonStatus(status.value);
        return '未知状态';
    }
    
    // 正常的字符串映射
    const descriptions = {
        'IDLE': '空闲',
        'BUSY': '忙碌',
        'OFFLINE': '离线',
        'DELIVERING': '配送中'
    };
    
    return descriptions[status] || status;
}

// 格式化日期
function formatDate(dateString) {
    if (!dateString) return '暂无日期信息';
    
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
    });
}

// 显示仪表盘视图
function showDashboardView() {
    hideAllViews();
    dashboardView.style.display = 'block';
    setActiveLink(dashboardLink);
    loadDashboardData(); // 刷新数据
}

// 显示用户管理视图
function showUsersView() {
    hideAllViews();
    usersView.style.display = 'block';
    setActiveLink(usersLink);
    // 加载用户数据
    loadUsersData();
}

// 显示配送员管理视图
function showDeliveryPersonsView() {
    hideAllViews();
    deliveryPersonsView.style.display = 'block';
    setActiveLink(deliveryPersonsLink);
    // 加载配送员数据
    loadDeliveryPersonsData();
}

// 显示订单管理视图
function showOrdersView() {
    hideAllViews();
    ordersView.style.display = 'block';
    setActiveLink(ordersLink);
    // 加载订单数据
    loadOrdersData();
}

// 显示统计分析视图
function showStatisticsView() {
    hideAllViews();
    statisticsView.style.display = 'block';
    setActiveLink(statisticsLink);
    // 加载统计数据
    loadStatisticsData();
}

// 隐藏所有视图
function hideAllViews() {
    dashboardView.style.display = 'none';
    usersView.style.display = 'none';
    deliveryPersonsView.style.display = 'none';
    ordersView.style.display = 'none';
    statisticsView.style.display = 'none';
}

// 设置活动链接
function setActiveLink(link) {
    // 移除所有链接的active类
    document.querySelectorAll('.nav-link').forEach(el => el.classList.remove('active'));
    // 添加active类到当前链接
    link.classList.add('active');
}

// 退出登录
function logout() {
    fetch('/logout', {
        method: 'POST',
        credentials: 'same-origin'
    })
    .then(() => {
        window.location.href = '/admin-login.html?logout=true';
    })
    .catch(error => {
        console.error('退出登录失败:', error);
        // 即使失败也重定向到登录页面
        window.location.href = '/admin-login.html';
    });
}

// 显示提示信息
// 显示提示消息
function showAlert(message, type = 'info') {
    const alertPlaceholder = document.getElementById('alertPlaceholder');
    if (!alertPlaceholder) {
        // 如果没有提示消息占位符，创建一个
        const container = document.querySelector('.container-fluid');
        const alertDiv = document.createElement('div');
        alertDiv.id = 'alertPlaceholder';
        alertDiv.className = 'position-fixed top-0 end-0 p-3';
        alertDiv.style.zIndex = '5000';
        container.appendChild(alertDiv);
    }
    
    const wrapper = document.createElement('div');
    wrapper.innerHTML = `
        <div class="alert alert-${type} alert-dismissible fade show" role="alert">
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    `;
    
    document.getElementById('alertPlaceholder').appendChild(wrapper);
    
    // 5秒后自动关闭
    setTimeout(() => {
        const alert = wrapper.querySelector('.alert');
        if (alert) {
            const bsAlert = new bootstrap.Alert(alert);
            bsAlert.close();
        }
    }, 5000);
}

// 查看订单详情（待实现）
function viewOrderDetail(orderNumber) {
    console.log('查看订单详情:', orderNumber);
    // 实现查看订单详情的功能
}

// 查看配送员详情（待实现）
function viewDeliveryPersonDetail(id) {
    console.log('查看配送员详情:', id);
    // 实现查看配送员详情的功能
}

// 加载用户数据
async function loadUsersData() {
    try {
        const response = await fetch(`${API_BASE_URL}/users`, {
            method: 'GET',
            credentials: 'same-origin'
        });
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const users = await response.json();
        displayUsers(users);
    } catch (error) {
        console.error('加载用户数据失败:', error);
        showAlert('加载用户数据失败，请刷新页面重试。', 'danger');
    }
}

// 显示用户数据
function displayUsers(users) {
    if (!users || users.length === 0) {
        usersTable.innerHTML = '<tr><td colspan="4" class="text-center">暂无用户数据</td></tr>';
        return;
    }
    
    const usersHtml = users.map(user => `
        <tr>
            <td>${user.id}</td>
            <td>${user.username}</td>
            <td>${formatRoles(user.roles)}</td>
            <td>
                <button class="btn btn-sm btn-outline-primary" onclick="viewUserDetail('${user.id}')">查看</button>
            </td>
        </tr>
    `).join('');
    
    usersTable.innerHTML = usersHtml;
}

// 格式化用户角色
function formatRoles(roles) {
    if (!roles || roles.length === 0) return '无角色';
    
    const roleMap = {
        'ROLE_USER': '用户',
        'ROLE_ADMIN': '管理员',
        'ROLE_DELIVERY': '配送员',
        'ROLE_DELIVERY_PERSON': '用户'  // 添加这一行，将ROLE_DELIVERY_PERSON映射为用户
    };
    
    return Array.from(roles).map(role => roleMap[role] || role).join(', ');
}

// 加载配送员数据
async function loadDeliveryPersonsData() {
    try {
        const response = await fetch(`${API_BASE_URL}/delivery-persons`, {
            method: 'GET',
            credentials: 'same-origin'
        });
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const deliveryPersons = await response.json();
        displayAllDeliveryPersons(deliveryPersons);
    } catch (error) {
        console.error('加载配送员数据失败:', error);
        showAlert('加载配送员数据失败，请刷新页面重试。', 'danger');
    }
}

// 显示所有配送员数据
function displayAllDeliveryPersons(deliveryPersons) {
    if (!deliveryPersons || deliveryPersons.length === 0) {
        deliveryPersonsFullTable.innerHTML = '<tr><td colspan="5" class="text-center">暂无配送员数据</td></tr>';
        return;
    }
    
    const deliveryPersonsHtml = deliveryPersons.map(person => `
        <tr>
            <td>${person.id}</td>
            <td>${person.name}</td>
            <td>${person.phone}</td>
            <td><span class="badge ${getDeliveryPersonStatusBadgeClass(person.status)}">${formatDeliveryPersonStatus(person.status)}</span></td>
            <td>
                <button class="btn btn-sm btn-outline-primary" onclick="viewDeliveryPersonDetail('${person.id}')">查看</button>
            </td>
        </tr>
    `).join('');
    
    deliveryPersonsFullTable.innerHTML = deliveryPersonsHtml;
}

// 加载订单数据
async function loadOrdersData() {
    try {
        const response = await fetch(`${API_BASE_URL}/orders`, {
            method: 'GET',
            credentials: 'same-origin'
        });
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const orders = await response.json();
        displayAllOrders(orders);
    } catch (error) {
        console.error('加载订单数据失败:', error);
        showAlert('加载订单数据失败，请刷新页面重试。', 'danger');
    }
}

// 显示所有订单数据
function displayAllOrders(orders) {
    if (!orders || orders.length === 0) {
        ordersTable.innerHTML = '<tr><td colspan="6" class="text-center">暂无订单数据</td></tr>';
        return;
    }
    
    const ordersHtml = orders.map(order => {
        // 只有待揽收和已揽收状态的订单才显示分配配送员按钮
        const showAssignButton = order.status === 'PENDING_COLLECTION' || order.status === 'COLLECTED';
        
        return `
        <tr>
            <td>${order.orderNumber}</td>
            <td>${order.shipperInfo ? order.shipperInfo.name : '未知'}</td>
            <td>${order.recipientInfo ? order.recipientInfo.name : '未知'}</td>
            <td><span class="badge ${getOrderStatusBadgeClass(order.status)}">${formatOrderStatus(order.status)}</span></td>
            <td>${formatDate(order.creationTime)}</td>
            <td>
                <div class="btn-group">
                    <button class="btn btn-sm btn-outline-primary" onclick="viewOrderDetail('${order.orderNumber}')">查看</button>
                    <button class="btn btn-sm btn-outline-warning" onclick="showUpdateStatusModal('${order.orderNumber}', '${order.status}')">修改状态</button>
                    ${showAssignButton ? `<button class="btn btn-sm btn-outline-info" onclick="showAssignModal('${order.orderNumber}')">分配配送员</button>` : ''}
                </div>
            </td>
        </tr>
        `;
    }).join('');
    
    ordersTable.innerHTML = ordersHtml;
}

// 加载统计数据
async function loadStatisticsData() {
    try {
        // 获取统计数据
        const statsResponse = await fetch(`${API_BASE_URL}/statistics`, {
            method: 'GET',
            credentials: 'same-origin'
        });
        
        if (!statsResponse.ok) {
            throw new Error(`HTTP error! status: ${statsResponse.status}`);
        }
        
        const stats = await statsResponse.json();
        
        // 获取所有订单和配送员数据用于图表
        const ordersResponse = await fetch(`${API_BASE_URL}/orders`, {
            method: 'GET',
            credentials: 'same-origin'
        });
        
        const deliveryPersonsResponse = await fetch(`${API_BASE_URL}/delivery-persons`, {
            method: 'GET',
            credentials: 'same-origin'
        });
        
        if (ordersResponse.ok && deliveryPersonsResponse.ok) {
            const orders = await ordersResponse.json();
            const deliveryPersons = await deliveryPersonsResponse.json();
            
            // 显示统计图表
            displayStatisticsCharts(orders, deliveryPersons);
        }
    } catch (error) {
        console.error('加载统计数据失败:', error);
        showAlert('加载统计数据失败，请刷新页面重试。', 'danger');
    }
}

// 显示统计图表
function displayStatisticsCharts(orders, deliveryPersons) {
    // 订单状态分布
    displayOrderStatusChart(orders);
    
    // 配送员状态分布
    displayDeliveryPersonStatusChart(deliveryPersons);
}

// 显示订单状态分布图表
function displayOrderStatusChart(orders) {
    const orderStatusChart = document.getElementById('orderStatusChart');
    if (!orderStatusChart) return;
    
    // 统计各状态订单数量
    const statusCounts = {};
    orders.forEach(order => {
        if (!statusCounts[order.status]) {
            statusCounts[order.status] = 0;
        }
        statusCounts[order.status]++;
    });
    
    // 准备图表数据
    const labels = [];
    const data = [];
    const backgroundColors = [];
    
    for (const status in statusCounts) {
        labels.push(formatOrderStatus(status));
        data.push(statusCounts[status]);
        backgroundColors.push(getChartColor(status));
    }
    
    // 创建简单的图表显示
    orderStatusChart.innerHTML = '';
    
    if (labels.length === 0) {
        orderStatusChart.innerHTML = '<div class="text-center py-5">暂无订单数据</div>';
        return;
    }
    
    // 创建简单的条形图
    const maxValue = Math.max(...data);
    const chartHtml = labels.map((label, index) => {
        const percentage = (data[index] / maxValue) * 100;
        return `
            <div class="mb-3">
                <div class="d-flex justify-content-between mb-1">
                    <span>${label}</span>
                    <span>${data[index]}个</span>
                </div>
                <div class="progress">
                    <div class="progress-bar" role="progressbar" style="width: ${percentage}%; background-color: ${backgroundColors[index]}" 
                        aria-valuenow="${percentage}" aria-valuemin="0" aria-valuemax="100"></div>
                </div>
            </div>
        `;
    }).join('');
    
    orderStatusChart.innerHTML = chartHtml;
}

// 显示配送员状态分布图表
function displayDeliveryPersonStatusChart(deliveryPersons) {
    const deliveryPersonStatusChart = document.getElementById('deliveryPersonStatusChart');
    if (!deliveryPersonStatusChart) return;
    
    // 统计各状态配送员数量
    const statusCounts = {};
    deliveryPersons.forEach(person => {
        if (!statusCounts[person.status]) {
            statusCounts[person.status] = 0;
        }
        statusCounts[person.status]++;
    });
    
    // 准备图表数据
    const labels = [];
    const data = [];
    const backgroundColors = [];
    
    for (const status in statusCounts) {
        labels.push(formatDeliveryPersonStatus(status));
        data.push(statusCounts[status]);
        backgroundColors.push(getChartColor(status, true));
    }
    
    // 创建简单的图表显示
    deliveryPersonStatusChart.innerHTML = '';
    
    if (labels.length === 0) {
        deliveryPersonStatusChart.innerHTML = '<div class="text-center py-5">暂无配送员数据</div>';
        return;
    }
    
    // 创建简单的条形图
    const maxValue = Math.max(...data);
    const chartHtml = labels.map((label, index) => {
        const percentage = (data[index] / maxValue) * 100;
        return `
            <div class="mb-3">
                <div class="d-flex justify-content-between mb-1">
                    <span>${label}</span>
                    <span>${data[index]}人</span>
                </div>
                <div class="progress">
                    <div class="progress-bar" role="progressbar" style="width: ${percentage}%; background-color: ${backgroundColors[index]}" 
                        aria-valuenow="${percentage}" aria-valuemin="0" aria-valuemax="100"></div>
                </div>
            </div>
        `;
    }).join('');
    
    deliveryPersonStatusChart.innerHTML = chartHtml;
}

// 获取图表颜色
function getChartColor(status, isDeliveryPerson = false) {
    if (isDeliveryPerson) {
        switch (status) {
            case 'IDLE': return '#28a745'; // 绿色
            case 'DELIVERING': return '#007bff'; // 蓝色
            case 'BUSY': return '#ffc107'; // 黄色
            case 'OFFLINE': return '#6c757d'; // 灰色
            default: return '#6c757d';
        }
    } else {
        switch (status) {
            case 'PENDING_PAYMENT': return '#6c757d'; // 灰色
            case 'PENDING_COLLECTION': return '#17a2b8'; // 青色
            case 'COLLECTED': return '#007bff'; // 蓝色
            case 'TRANSPORTING': return '#007bff'; // 蓝色
            case 'OUT_FOR_DELIVERY': return '#ffc107'; // 黄色
            case 'DELIVERY_FAILED': return '#dc3545'; // 红色
            case 'SIGNED': return '#28a745'; // 绿色
            case 'COMPLETED': return '#28a745'; // 绿色
            case 'CANCELLED': return '#dc3545'; // 红色
            default: return '#6c757d';
        }
    }
}

// 查看用户详情（待实现）
function viewUserDetail(id) {
    console.log('查看用户详情:', id);
    // 实现查看用户详情的功能
    showAlert(`用户详情功能正在开发中 (ID: ${id})`, 'info');
}

// 显示订单状态修改模态框
// 在显示状态更新模态框前检查当前状态
function showUpdateStatusModal(orderNumber, currentStatus) {
    // 如果订单已经是终态，显示提示并阻止操作
    if (currentStatus === 'COMPLETED' || currentStatus === 'CANCELLED' || currentStatus === 'REFUNDED') {
        showAlert(`订单状态为${getStatusDescription(currentStatus)}，不能再修改状态`, 'warning');
        return;
    }
    
    // 设置订单号
    document.getElementById('statusOrderNumber').value = orderNumber;
    // 移除这一行，因为HTML中没有这个元素
    // document.getElementById('currentOrderStatus').textContent = getStatusDescription(currentStatus);
    
    // 根据当前状态，限制可选的下一状态
    const statusSelect = document.getElementById('newStatus');
    statusSelect.innerHTML = ''; // 清空现有选项
    
    // 根据当前状态添加合法的下一状态选项
    const nextStatuses = getValidNextStatuses(currentStatus);
    nextStatuses.forEach(status => {
        const option = document.createElement('option');
        option.value = status;
        option.textContent = getStatusDescription(status);
        statusSelect.appendChild(option);
    });
    
    // 显示模态框
    const modal = new bootstrap.Modal(document.getElementById('updateStatusModal'));
    modal.show();
}

// 获取状态描述
function getStatusDescription(status) {
    const descriptions = {
        'PENDING_PAYMENT': '待支付',
        'PENDING_COLLECTION': '待揽收',
        'COLLECTED': '已揽收',
        'TRANSPORTING': '运输中',
        'OUT_FOR_DELIVERY': '派送中',
        'DELIVERY_FAILED': '派送失败',
        'SIGNED': '已签收',
        'COMPLETED': '已完成',
        'CANCELLED': '已取消',
        'REFUNDED': '已退款'
    };
    return descriptions[status] || status;
}

// 获取当前状态可以转换到的下一状态列表
function getValidNextStatuses(currentStatus) {
    switch (currentStatus) {
        case 'PENDING_PAYMENT':
            return ['PENDING_COLLECTION', 'CANCELLED'];
        case 'PENDING_COLLECTION':
            return ['COLLECTED', 'CANCELLED'];
        case 'COLLECTED':
            return ['TRANSPORTING'];
        case 'TRANSPORTING':
            return ['OUT_FOR_DELIVERY'];
        case 'OUT_FOR_DELIVERY':
            return ['SIGNED', 'DELIVERY_FAILED'];
        case 'DELIVERY_FAILED':
            return ['OUT_FOR_DELIVERY'];
        case 'SIGNED':
            return ['COMPLETED', 'REFUNDED'];
        default:
            return [];
    }
}

// 显示分配配送员模态框
async function showAssignModal(orderNumber) {
    document.getElementById('assignOrderNumber').value = orderNumber;
    
    // 加载配送员列表
    try {
        const response = await fetch(`${API_BASE_URL}/delivery-persons`, {
            method: 'GET',
            credentials: 'same-origin'
        });
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const deliveryPersons = await response.json();
        const deliveryPersonSelect = document.getElementById('deliveryPersonId');
        
        // 清空现有选项
        deliveryPersonSelect.innerHTML = '<option value="">-- 请选择配送员 --</option>';
        
        // 添加配送员选项
        deliveryPersons.forEach(person => {
            const option = document.createElement('option');
            option.value = person.id;
            option.textContent = `${person.name} (${person.phone})`;
            deliveryPersonSelect.appendChild(option);
        });
        
        const modal = new bootstrap.Modal(document.getElementById('assignModal'));
        modal.show();
    } catch (error) {
        console.error('加载配送员列表失败:', error);
        showAlert('加载配送员列表失败，请刷新页面重试。', 'danger');
    }
}

// 更新订单状态
async function updateOrderStatus() {
    const orderNumber = document.getElementById('statusOrderNumber').value;
    const newStatus = document.getElementById('newStatus').value;
    const description = document.getElementById('statusDescription').value;
    
    try {
        const response = await fetch(`${API_BASE_URL}/orders/${orderNumber}/status`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            credentials: 'same-origin',
            body: JSON.stringify({
                status: newStatus,
                description: description
            })
        });
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const result = await response.json();
        
        // 关闭模态框
        const modal = bootstrap.Modal.getInstance(document.getElementById('updateStatusModal'));
        modal.hide();
        
        // 显示成功消息
        showAlert('订单状态已成功更新', 'success');
        
        // 重新加载订单数据
        loadOrdersData();
    } catch (error) {
        console.error('更新订单状态失败:', error);
        showAlert('更新订单状态失败，请重试。', 'danger');
    }
}

// 手动分配配送员
async function assignDeliveryPerson() {
    const orderNumber = document.getElementById('assignOrderNumber').value;
    const deliveryPersonId = document.getElementById('deliveryPersonId').value;
    
    if (!deliveryPersonId) {
        showAlert('请选择配送员', 'warning');
        return;
    }
    
    try {
        const response = await fetch(`${API_BASE_URL}/orders/${orderNumber}/assign`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            credentials: 'same-origin',
            body: JSON.stringify({
                deliveryPersonId: deliveryPersonId
            })
        });
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const result = await response.json();
        
        // 关闭模态框
        const modal = bootstrap.Modal.getInstance(document.getElementById('assignModal'));
        modal.hide();
        
        // 显示成功消息
        showAlert('配送员已成功分配', 'success');
        
        // 重新加载订单数据
        loadOrdersData();
    } catch (error) {
        console.error('分配配送员失败:', error);
        showAlert('分配配送员失败，请重试。', 'danger');
    }
}



// 添加事件监听器
document.addEventListener('DOMContentLoaded', function() {
    // 订单状态更新按钮
    const updateStatusBtn = document.getElementById('updateStatusBtn');
    if (updateStatusBtn) {
        updateStatusBtn.addEventListener('click', updateOrderStatus);
    }
    
    // 手动分配配送员按钮
    const assignBtn = document.getElementById('assignBtn');
    if (assignBtn) {
        assignBtn.addEventListener('click', assignDeliveryPerson);
    }
});